package com.lagou.service.impl;

import com.lagou.dao.AuthCodeDao;
import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private AuthCodeDao authCodeDao;
    @Reference
    private EmailService emailService;

    @Override
    public String sendCode(String email) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //生成6位验证码
        int hashCode = UUID.randomUUID().toString().hashCode();
        String code = String.valueOf(hashCode).substring(1, 7);
        //发送验证码到短信
        emailService.sendCodeTOEmail(code,email);
        //保存验证码到mysql数据库
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        Date createtime = new Date();
        Date expiretime = new Date(createtime.getTime() + 10 * 60 * 1000);
        authCode.setCreatetime(createtime);
        authCode.setExpiretime(expiretime);
        authCodeDao.save(authCode);
        return "success";
    }

    @Override
    public AuthCode getAuthCodeByEmailAndCode(String email,String code) {
        //根据email和code获取AuthCode
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        Optional<AuthCode> optional = authCodeDao.findOne(example);
        if(optional.isEmpty()){
            return null;
        }
        AuthCode authCodeMsg = optional.get();
        return authCodeMsg;
    }
}
